package com.baidu.sggc.service;

import com.alibaba.fastjson.JSON;
import com.baidu.sggc.data.req.ModelCreateReq;
import com.baidu.sggc.data.req.ModelListReq;
import com.baidu.sggc.data.req.ModelUpdateReq;
import com.baidu.sggc.data.resp.Page;
import com.baidu.sggc.entity.ModelInfo;
import com.baidu.sggc.entity.ModelInfoExt;
import com.baidu.sggc.entity.UserContext;
import com.baidu.sggc.mapper.ModelInfoMapper;
import com.baidu.sggc.third.mb.model.MbModelApi;
import com.baidu.sggc.third.mb.model.ModelListReqDto;
import com.baidu.sggc.third.mb.model.MbProjectApi;
import com.baidu.sggc.third.mb.model.ModelListRespDto;
import com.baidu.sggc.third.mb.model.ModelListRespDto.ModelItem;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * <p>
 * 模型信息表 服务实现类
 * </p>
 *
 * @author lianglin
 * @since 2025-02-13
 */
@Service
public class ModelInfoService {

  @Autowired
  private MbModelApi mbModelApi;

  @Autowired
  private MbProjectApi projectApi;

  @Autowired
  private ModelInfoMapper modelInfoMapper;

  public Page<ModelInfo> getModelInfoList(ModelListReq req) {
    try {
      Thread.sleep(1000); // 模拟延时，便于压测
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }
    String modelName = req.getModelName();
    if (StringUtils.isNotBlank(modelName)) {
      // 对 LIKE 特殊字符转义
      modelName = escapeLikeParam(modelName.trim());
      req.setModelName(modelName);
    }

    PageHelper.startPage(req.getPageNum(), req.getPageSize());
    List<ModelInfo> modelInfoList = modelInfoMapper.list(req);
    PageInfo<ModelInfo> pageInfo = new PageInfo<>(modelInfoList);

    if (!CollectionUtils.isEmpty(modelInfoList)) {
      modelInfoList.forEach(modelInfo -> {
        modelInfo.setUserName(UserContext.getUserName());
        if (StringUtils.isNotBlank(modelInfo.getExtJson())) {
          modelInfo.setExtJsonObject(JSON.parseObject(modelInfo.getExtJson(), ModelInfoExt.class));
        }
      });
    }

    return new Page<>(pageInfo.getTotal(), modelInfoList, pageInfo.isHasNextPage());
  }

  /**
   * 转义方法建议放到工具类
   */
  public static String escapeLikeParam(String param) {
    if (param == null) {
      return null;
    }
    // 只转义 %, _
    return param.replace("%", "\\%").replace("_", "\\_");
  }


  public ModelInfo getModelDetail(String modelId) {
    return modelInfoMapper.selectById(modelId);
  }

  public void createModel(ModelCreateReq modelCreateReq) {
    ModelInfo modelInfo = new ModelInfo();
    BeanUtils.copyProperties(modelCreateReq, modelInfo);
    // 设置创建人信息
    String userId = UserContext.getUserId();
    if (userId != null) {
      modelInfo.setCreateId(userId);
    }
    modelInfoMapper.insert(modelInfo);
  }

  public void updateModel(ModelUpdateReq updateReq) {
    // 设置更新人信息
    String userId = UserContext.getUserId();
    if (userId != null) {
      updateReq.setUpdateId(userId);
    }
    modelInfoMapper.updateModel(updateReq);
  }

  public List<ModelInfo> queryModelsByProjectId(String projectId) {
    List<ModelInfo> modelInfoList = null;
    try {
      ModelListReqDto modelListReqDto = new ModelListReqDto();
      ModelListRespDto modelListRespDto  = mbModelApi.queryModel(modelListReqDto);
      if (modelListRespDto != null && modelListRespDto.getStatus() == 0){
        modelInfoList = new ArrayList<>();
        for (ModelItem item : modelListRespDto.getItems()) {
          ModelInfo modelInfo = new ModelInfo();
          modelInfo.setModelId( item.getAssetId());
          modelInfo.setTechType( item.getTechType() + "");
          modelInfo.setModelName( item.getChineseName());
          String dataType =  ArrayUtils.isEmpty(item.getDataType()) ? "" : StringUtils.join(item.getDataType(), ",");
          modelInfo.setDataType(dataType);
          String frameworkType =  ArrayUtils.isEmpty(item.getFramework()) ? "" : StringUtils.join(item.getFramework(), ",");
          modelInfo.setFrameworkType(frameworkType);
          modelInfo.setLicense(item.getLicense());
          modelInfoList.add(modelInfo);
        }
      }
    }catch (Exception e){
       throw new RuntimeException("查询模型失败");
    }
    return modelInfoList;

  }

  public void queryProject() {
    projectApi.queryProjectList();
  }
}
